package collection.MyList;

import java.util.Arrays;

public class MyArrayList {
    private int[] elem;
    private  int usdSize;//代表当前顺序表当中的有效数据个数
    private static final int DEFAULT_SIZE = 10;//定义顺序表容量
    public MyArrayList(){
        //默认容量
        this.elem = new int[DEFAULT_SIZE];
    }

    /**
     * 指定容量
     * @param initCapacity
     */
    public MyArrayList(int initCapacity){
        //指定容量
        this.elem = new int[initCapacity];
    }

    public void display(){
        //遍历打印数组
        for (int i = 0; i < usdSize; i++) {
            System.out.print(this.elem[i]+" ");
        }
        System.out.println();
    }
    //新增元素，默认在数组的最后新加
    public void add(int data){
        if (isFull()) {
            //扩容
            this.elem = Arrays.copyOf(this.elem,10+elem.length);
        }
            this.elem[this.usdSize] = data;
            this.usdSize++;
    }
    public boolean isFull(){
        //判断数组是否存满
        if(this.usdSize==this.elem.length){
            return true;
        }
        return false;
    }
    public void add(int data,int pos){
        //在pos位置新增
        if (pos < 0 || pos > usdSize){
            //判断pos位置是否合法
            throw new PosOutOfBoundsExeption(pos + "pos位置不合法");
        }
        if (isFull()){
            this.elem = Arrays.copyOf(this.elem,10+elem.length);
        }
        for (int i = this.usdSize; i >= pos; i--) {
            this.elem[i+1] = this.elem[i];
        }
        this.elem[pos] = data;
        this.usdSize++;
    }

    public boolean contains(int toFind){
        //判断是否包含某个元素
        for (int i = 0; i < this.usdSize; i++) {
            if (this.elem[i] == toFind){
                return true;
            }
        }
        return false;
    }
    public int indexOf(int toFind){
        //查找某个元素对应的位置
        for (int i = 0; i < this.usdSize; i++) {
            if (this.elem[i] == toFind){
                return i;
            }
        }
        return -1;
    }
    public int get(int pos){
        //获取pos位置的元素
        checkPos(pos);
        return elem[pos];
    }
    public void set(int pos,int value){
        //将pos位置的元素设为value
        checkPos(pos);
        this.elem[pos] = value;
    }
    private void checkPos(int pos){
        if (pos < 0 || pos >= this.usdSize){
            throw new PosOutOfBoundsExeption(pos + "pos位置不合法");
        }
    }

    public void remove(int toRemove){
        //删除指定元素
        int index = indexOf(toRemove);
        if (index == -1){
            System.out.println("没有这个元素");
            return;
        }
        for (int i = index; i < this.usdSize - 1; i++) {
            this.elem[i] = this.elem[i + 1];
        }
        this.usdSize--;
    }
    public int size(){
        return usdSize;
    }
    public void clean(){
        //清空顺序表
        /*
        //当顺序表为引用类型时
        for (int i = 0;i < this.usdSize;i++){
            elem[i] = null;
        }
         */
        this.usdSize = 0;
    }
}
